export interface RandomReleaseParams {
  startDate: Date
  endDate: Date
  year: number
  month0: number
  countRange?: [number, number]
  quotaRange?: [number, number]
}

export interface RandomReleaseResult {
  availableDates: string[] // DD-MM-YYYY
  quotas: Record<string, number> // key: DD-MM-YYYY => quota count
}

function clamp(n: number, min: number, max: number): number {
  return Math.max(min, Math.min(max, n))
}

function randInt(min: number, max: number): number {
  const lo = Math.ceil(min)
  const hi = Math.floor(max)
  return Math.floor(Math.random() * (hi - lo + 1)) + lo
}

export function generateRandomRelease(params: RandomReleaseParams): RandomReleaseResult {
  const { startDate, endDate, year, month0 } = params
  const [cntMin, cntMax] = params.countRange || [2, 4]
  const [qMin, qMax] = params.quotaRange || [1, 3]

  const daysInMonth = new Date(year, month0 + 1, 0).getDate()
  const candidates: string[] = []
  for (let d = 1; d <= daysInMonth; d++) {
    const y = year
    const m = String(month0 + 1).padStart(2, '0')
    const dd = String(d).padStart(2, '0')
    const dmy = `${dd}-${m}-${y}`
    const dt = new Date(y, month0, d)
    dt.setHours(0, 0, 0, 0)
    // 排除周六日（0=周日, 6=周六）
    const dow = dt.getDay()
    if (dow === 0 || dow === 6)
      continue
    if (dt >= startDate && dt <= endDate)
      candidates.push(dmy)
  }

  if (candidates.length === 0)
    return { availableDates: [], quotas: {} }

  const count = clamp(randInt(cntMin, cntMax), 1, candidates.length)
  const picked: Set<string> = new Set()
  while (picked.size < count && picked.size < candidates.length) {
    const idx = randInt(0, candidates.length - 1)
    picked.add(candidates[idx])
  }

  const quotas: Record<string, number> = {}
  const out: string[] = []
  for (const d of picked) {
    const q = clamp(randInt(qMin, qMax), 1, 50)
    quotas[d] = q
    out.push(d)
  }

  return { availableDates: out.sort(), quotas }
}
